<template>
	<view class="register-pay page">
		<UserDate />

		<view class="tcard">
			<view class="title">
				挂号信息
			</view>
			<view class="tform">
				<view class="tform-item">
					<view class="label">
						预约科室
					</view>
					<view class="value">
						{{routeParams.ksmc}}
					</view>
				</view>
				<view class="tform-item">
					<view class="label">
						医生姓名
					</view>
					<view class="value">
						{{routeParams.ysmc}}
					</view>
				</view>
				<view class="tform-item" v-if="routeParams.ghrq">
					<view class="label">
						预约时间
					</view>
					<view class="value">
						{{routeParams.ghrq|transRQ}}
					</view>
				</view>
				<view class="tform-item" v-if="routeParams.ghsjd">
					<view class="label">
						就诊时段
					</view>
					<view class="value">
						{{routeParams.ghsjd}}
					</view>
				</view>
				<view class="tform-item" style="border: none;" v-if="routeParams.ghsjd">
					<view class="label">
						挂号费用
					</view>
					<view class="value">
						<!-- ￥{{params.zje||'0'}} -->
						￥{{params.zje||routeParams.ghje||'0'}}
					</view>
				</view>
				<view class="info-box">
					<view class="info-box-row">
						<label>挂号费</label>￥{{params.ghf||routeParams.ghf||'0'}}
					</view>
					<view class="info-box-row">
						<label>诊疗费</label>￥{{params.zlf||routeParams.zlf||'0'}}
					</view>
				</view>

			</view>
		</view>
		<view class="check-box">
			<radio :checked="check" @click="checkChange" />
			<view class="check-txt">我已阅读并了解《挂号须知》</view>
		</view>
		<view class="btn" :style="{opacity:check?'1':'0.4'}" @click="onPay">
			确认预约
		</view>
		<Loading :load='load' />
		<Dialog :show.sync="show" title="请认真核对以下挂号信息" @confirm="confirm">
			<view class="tform no-border">
				<view class="tform-item">
					<view class="">
						就诊人
					</view>
					<view class="" style="color: #3E81F7;">
						{{userInfo.name}}
					</view>
				</view>
				<view class="tform-item">
					<view class="">
						预约科室
					</view>
					<view class="">
						{{routeParams.ksmc}}
					</view>
				</view>
				<!-- <view class="tform-item">
          <view class="">
            科室位置
          </view>
          <view class="">
            xxxx
          </view>
        </view> -->
				<view class="tform-item">
					<view class="">
						预约医生
					</view>
					<view class="">
						{{routeParams.ysmc}}
					</view>
				</view>
				<view class="tform-item">
					<view class="">
						预约时间
					</view>
					<view class="">
						{{routeParams.ghrq|transRQ}}<br>
						{{routeParams.ghsjd}}
					</view>
				</view>
			</view>
		</Dialog>
	</view>
</template>

<script>
	import {
		themeColorLight
	} from '@/static/js/theme.js'
	import Loading from '@/components/Load/index.vue'
	import {
		getAppointment,
		cancelAppointment,
		poPayRegister
	} from '@/api/register.js'
	import {
		mapGetters,
		mapActions
	} from 'vuex'
	import dayjs from 'dayjs'
	import tradePay from '@/utils/pay.js'
	import {
		getPayStatusMY
	} from "@/api/system.js"
	import UserDate from '@/components/UserInfo/user-date.vue'

	export default {
		components: {
			Loading,
			UserDate
		},
		data() {
			return {
				themeColorLight,
				load: false,
				params: '',
				routeParams: '',
				fromYYZT: 0, // 预约状态1 表示从我的挂号页面来 不需要展示取消预约 因为我的挂号页面已展示了取消按钮
				timeNumber: 10000,
				timer: null,
				check: false,
				show: false
			}
		},
		computed: {
			...mapGetters(['userInfo'])
		},
		async onLoad(op) {

			if (op.yyzt) {
				this.fromYYZT = op.yyzt
				if (op.yyzt == 1) {
					this.routeParams = JSON.parse(op.params)
				}
			} else if (op.params) {
				this.routeParams = JSON.parse(op.params)
			}
			await this.$onLaunched
			if (!this.userInfo.patId) {
				// uni.navigateTo({
				// 	url:'/pages/Login/index'
				// })
				return
			}
			// this.initData()
		},
		filters: {
			transRQ(val) {
				return dayjs(val).format('YYYY-MM-DD')
			}
		},
		methods: {
			...mapActions(['createPay']),
			onPay() {
				if (!this.check) {
					return this.$u.toast('请先阅读并了解挂号须知')
				}
				// if(!this.params){
				// 	return
				// }

				this.show = true
				return
				if (this.params.ysje === 0) {
					this.toRegister()
				} else {
					this.toPay()
				}
			},
			checkChange() {
				this.check = !this.check
			},
			toRegister() {
				let params = {
					ysje: this.params.ysje,
					patId: this.userInfo.patId,
					sjh: this.params.sjh,
					yyxh: this.params.yyxh,
					ghxh: this.params.ghxh,
				}
				this.load = true;
				poPayRegister(params).then(data => {
					this.load = false
					this.$u.toast('预约挂号成功！')
					uni.reLaunch({
						url: '/pages/Index'
					})
				}).catch(e => {
					this.load = false
				})
			},
			toPay() {
				let params = {
					money: this.params.ysje,
					patId: this.userInfo.patId,
					sjh: this.params.sjh,
					tradeType: 1,
				}
				this.load = true;
				this.createPay(params).then((data) => {
					this.load = false;
					let paymentData;
					// #ifdef MP-ALIPAY
					paymentData = data.tradeNo
					// #endif
					// #ifndef MP-ALIPAY
					paymentData = {
						timeStamp: data.timeStamp,
						nonceStr: data.nonceStr,
						package: data.weChatPackage,
						signType: data.signType,
						paysign: data.paySign
					}
					// #endif
					if (paymentData) {
						// #ifdef MP-ALIPAY
						tradePay(paymentData, status => {
							let info = {
								outTradeNo: data.outTradeNo
							}
							this.getStatus(info, 1000)
						})
						// #endif
						// #ifndef MP-ALIPAY
						tradePay(paymentData)
						// #endif
					} else {
						this.$u.toast('系统错误')
					}
				}).catch(e => {
					this.load = false
				})
			},
			toPay() {
				let params = {
					money: this.params.ysje,
					patId: this.userInfo.patId,
					sjh: this.params.sjh,
					tradeType: 1,
				}
				this.load = true;
				this.createPay(params).then((data) => {
					this.load = false;
					let paymentData;
					paymentData = {
						body: data.hisOrderId,
						orderId: data.hisOrderId,
						// payMoney: this.params.ysje,
						payMoney: '0.01',
						spbCreIp: '127.0.0.1',
						openId: this.userInfo.userId,
						account: this.userInfo.userId
					}

					pay(paymentData).then(res => {
						this.onBridgeReady(res)
					})
				}).catch(e => {
					this.load = false
				})
			},
			pay() {
				const data = {
					body: this.pkg.pkgName,
					orderId: this.opt.orderId,
					// payMoney: this.params.ysje,
					payMoney: '0.01',
					spbCreIp: '127.0.0.1',
					openId: this.userInfo.userId,
					account: this.userInfo.userId
				}
				pay(data).then(res => {
					this.onBridgeReady(res)
				})
			},
			onBridgeReady(res) {
				WeixinJSBridge.invoke('getBrandWCPayRequest', {
						"appId": res.appId, //公众号ID，由商户传入     
						"timeStamp": res.timeStamp, //时间戳，自1970年以来的秒数     
						"nonceStr": res.nonceStr, //随机串     
						"package": res.package,
						// "signType": "RSA",     //微信签名方式：     
						"signType": "MD5", //微信签名方式：
						"paySign": res.paySign //微信签名 
					},
					function(res) {
						if (res.err_msg == "get_brand_wcpay_request:ok") {
							// 使用以上方式判断前端返回,微信团队郑重提示：
							//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
							// alert('跳转成功页面')

							// this.$u.toast('支付成功')
							uni.redirectTo({
								url: '/pages/Index'
							})
						}
					});
			},
			confirm() {
				getAppointment({
					...this.routeParams
				}).then(data => {
					this.load = false
					this.params = data || ''
					uni.navigateTo({
						url: `./cashier?routeParams=${JSON.stringify(this.routeParams)}&params=${JSON.stringify(this.params)}`
					})
				}).catch(e => {
					this.load = false
					this.params = ""
					if (e.retCode === 'C0006') {
						this.$u.toast('用户已预约，请前往我的挂号信息中完成支付')
						uni.redirectTo({
							url: '/pages/Personal/Myregister/index'
						})
					}
				})

			},
			// 轮询
			getStatus(info, refreshTime) {
				this.load = true
				this.timer = setInterval(() => {
					if (this.timeNumber < 0) {
						this.clearTimer()
						this.$u.toast('业务处理状态未知，请以具体消息通知为准')
					}
					this.timeNumber -= refreshTime
					getPayStatusMY(info).then(data => {
						if (data) {
							let msg = ''
							if (data.tradeStatus === 'WAIT_BUYER_PAY' || data.tradeStatus ===
								'TRADE_CLOSED') {
								this.$u.toast('用户未支付')
								this.clearTimer()
							} else {
								if (data.payStatus === 4) {
									this.clearTimer()
									this.$u.toast('支付成功')
									uni.redirectTo({
										url: '/pages/Index'
									})
								} else if (data.payStatus === 7) {
									this.clearTimer()
									this.$u.toast('业务处理失败，已退款')
								}
							}
						} else {
							this.clearTimer()
						}
					}).catch(e => {
						this.clearTimer()
					})
				}, refreshTime)
			},
			// 清除计时器
			clearTimer() {
				this.load = false
				if (this.timer) {
					clearInterval(this.timer)
					this.timer = null
				}
			},
			initData() {
				this.load = true;
				getAppointment({
					...this.routeParams
				}).then(data => {
					this.load = false
					this.params = data || ''
				}).catch(e => {
					this.load = false
					this.params = ""
					if (e.retCode === 'C0006') {
						this.$u.toast('用户已预约，请前往我的挂号信息中完成支付')
						uni.redirectTo({
							url: '/pages/Personal/Myregister/index'
						})
					}
				})
			},
			onCancle() {
				let params = {
					ghrq: this.params.ghrq,
					patId: this.userInfo.patId,
					yyxh: this.params.yyxh
				}
				this.load = true
				cancelAppointment(params).then(data => {
					this.load = false
					this.$u.toast('预约取消成功')
					uni.navigateBack()
				}).catch(e => {
					this.load = false
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.check-box {
		display: flex;
		justify-content: flex-start;
		align-items: center;

		::v-deep.uni-radio-input {
			width: 32upx;
			height: 32upx;
		}

		.check-txt {
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 24upx;
			color: rgba(0, 0, 0, 0.7);
			margin-left: 12upx;
		}
	}

	.btn {
		// width: ;
		margin: 80upx;
		height: 80upx;
		line-height: 80upx;
		border-radius: 80upx;
		background-color: $theme-color;
		color: #FFF;
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 32upx;
		line-height: 80upx;
		text-align: center;
	}
</style>